<?php defined('SYSPATH') or die('No direct script access.');

class Model_Member_Grade extends ORM
{

    /**
     * @param $params
     * @return void
     * @throws Kohana_Exception
     * 升级处理
     */
    public static function grade_change_handler($params)
    {
        $db = Database::instance();
        $db->begin();
        try {
            $member_id   = $params['member_id'];
            $member_info = $params['member_info'];//已绑定的等级信息
            $new_grade   = $params['new_grade'];//新等级信息
            $org_grade   = $params['current_grade'];//当前等级信息
            $equity      = $params['equity'];

            //是否已赠送
            $is_gift = DB::select()->from('member_grade_change_record')
                ->where('member_id','=',$member_id)
                ->and_where('new_grade_id','=',$new_grade['id'])
                ->execute()->current();

            //升级处理 老用户未绑定等级或满足升级条件时 变更等级信息
            if((!$member_info['grade_id'] || $new_grade['current']>$org_grade['current'])){

                //0永久有效 存在时间戳时为时限有效
                $grade_expire_time = 0;
                if($new_grade['expiration_time'] && $new_grade['valid_type']==2){
                    $grade_expire_time = time() + $new_grade['expiration_time'] * 86400;
                }
                DB::update('member')->set([
                    'grade_id'          => $new_grade['id'],
                    'grade_name'        => $new_grade['name'],
                    'grade_expire_time' => $grade_expire_time
                ])->where('mid', '=', $member_id)->execute();
                if($equity && !$is_gift){
                    self::upgrade_gift_handler($member_id, $member_info, $new_grade, $equity);
                }
            }

            //到期降级处理
            if($member_info['grade_expire_time']>0 && time()>$member_info['grade_expire_time'] && $member_info['grade_id']){
                self::lower_grade_handler($member_id, $member_info);
            }

            //生日赠送处理
            $to_day     = date('m-d');
            $birth_date = '';
            if($member_info['birth_date'] && $member_info['birth_date']!='0/0/0'){
                $birth_date = date('m-d',strtotime($member_info['birth_date']));
            }
            if(empty($birth_date) && $member_info['cardid']){
                //从身份证号中提取出生日期
                $birth_date = substr($member_info['cardid'],6,4).'-'.substr($member_info['cardid'],10,2).'-'.substr($member_info['cardid'],12,2);
                $birth_date = date('m-d',strtotime($birth_date));
            }
            //未过期或永久有效时才赠送
            if($to_day == $birth_date && $equity['birthday_coupon_num'] && ($member_info['grade_expire_time']>time() || $member_info['grade_expire_time']<1)){
                $start = strtotime(date('Y').'-01-01');
                $end   = strtotime(date('Y').'-12-31');
                $is_gift = DB::select()->from('member_grade_change_record')
                    ->where('member_id','=',$member_id)
                    ->and_where('equity_id','=',3)
                    ->and_where('addtime','>=',$start)
                    ->and_where('addtime','<=',$end)
                    ->execute()->current();
                if(!$is_gift){
                    self::birthday_gift_handler($member_id, $equity);
                }
            }

            $db->commit();
        } catch (Exception $e) {
            $db->rollback();
        }
    }

    /**
     * @param $member_id
     * @param $member_info
     * @param $new_grade
     * @param $equity
     * @return void
     * @throws Kohana_Exception
     * 升级处理
     */
    public static function upgrade_gift_handler($member_id, $member_info, $new_grade, $equity)
    {
        $record = [
            'member_id'    => $member_id,
            'equity_id'    => '',
            'org_grade_id' => $member_info['grade_id'],
            'new_grade_id' => $new_grade['id'],
            'type'         => 1,
            'addtime'      => time(),
        ];
        $data   = [];
        //积分赠送
        if (in_array(1, $equity['equity_id']) && $equity['gift_jifen'] > 0) {
            $data['jifen'] = bcadd($member_info['jifen'], $equity['gift_jifen'], 2);
            Model_Member_Jifen::add_jifen_log($member_id, "会员等级升至【{$new_grade['name']}】赠送{$equity['gift_jifen']}积分。", $equity['gift_jifen'], 2);
            $record['equity_id'] = '1';
        }
        //升级券赠送
        if (in_array(4, $equity['equity_id']) && $equity['upgrade_coupon_num']) {
            $upgrade_coupon = json_decode($equity['upgrade_coupon_num'], true);
            foreach ($upgrade_coupon as $cid => $num) {
                for ($i = 0; $i < $num; $i++) {
                    $arr = [
                        'mid'      => $member_id,
                        'cid'      => $cid,
                        'totalnum' => 1,
                        'is_give'  => 1,
                        'givetime' => time()
                    ];
                    DB::insert('member_coupon', array_keys($arr))->values(array_values($arr))->execute();
                }
            }
            $record['equity_id'] = $record['equity_id']?$record['equity_id'].',4':'4';
        }
        //积分抽奖次数赠送
        if (in_array(6, $equity['equity_id'])) {
            $data['jifen_lottery_num'] = bcadd($member_info['jifen_lottery_num'], $equity['lottery_num']);
            $record['equity_id'] = $record['equity_id']?$record['equity_id'].',6':'6';
        }

        if (count($data) > 0) {
            DB::update('member')->set($data)->where('mid', '=', $member_id)->execute();
            DB::insert('member_grade_change_record', array_keys($record))->values(array_values($record))->execute();
        }
    }

    /**
     * @param $member_id
     * @param $member_info
     * @return void
     * 降级处理
     */
    public static function lower_grade_handler($member_id, $member_info)
    {
        //当前等级
        $current_grade = DB::select()->from('member_grade')->where('id','=',$member_info['grade_id'])->execute()->current();
        //降至等级
        $grade_id = $current_grade['grade_id']?:DB::select()->from('member_grade')->where('is_system','=',1)->execute()->get('id');
        $new_grade = DB::select()->from('member_grade')->where('id','=',$grade_id)->execute()->current();
        $grade_expire_time = 0;
        if($new_grade['expiration_time'] && $new_grade['valid_type']==2){
            $grade_expire_time = time() + $new_grade['expiration_time'] * 86400;
        }
        DB::update('member')->set([
            'grade_id'          => $new_grade['id'],
            'grade_name'        => $new_grade['name'],
            'grade_expire_time' => $grade_expire_time,
        ])->where('mid', '=', $member_id)->execute();
    }

    /**
     * @param $member_id
     * @param $equity
     * @return void
     * @throws Kohana_Exception
     * 生日处理
     */
    public static function birthday_gift_handler($member_id, $equity)
    {
        $record = [
            'member_id'    => $member_id,
            'equity_id'    => '3',
            'type'         => 2,
            'addtime'      => time(),
        ];
        $birthday_coupon = json_decode($equity['birthday_coupon_num'], true);
        if($birthday_coupon ){
            foreach ($birthday_coupon as $cid => $num) {
                for ($i = 0; $i < $num; $i++) {
                    $arr = [
                        'mid'      => $member_id,
                        'cid'      => $cid,
                        'totalnum' => 1,
                        'is_give'  => 1,
                        'givetime' => time()
                    ];
                    DB::insert('member_coupon', array_keys($arr))->values(array_values($arr))->execute();
                }
            }
            DB::insert('member_grade_change_record', array_keys($record))->values(array_values($record))->execute();
        }
    }

    /**
     * @param $member
     * @return void
     * @throws Kohana_Exception
     * 新用户注册处理
     */
    public static function new_user_gift($member)
    {
        $grade_id = DB::select()->from('member_grade')->where('is_system','=',1)->execute()->get('id');
        $equity = self::get_equity($grade_id);
        if($equity && in_array(5,$equity['equity_id']) && $equity['new_user_coupon_id']){
            $coupon_id = json_decode($equity['new_user_coupon_num'],true);
            foreach ($coupon_id as $cid => $num) {
                for ($i = 0; $i < $num; $i++) {
                    $arr = [
                        'mid'      => $member['mid'],
                        'cid'      => $cid,
                        'totalnum' => 1,
                        'is_give'  => 1,
                        'givetime' => time()
                    ];
                    DB::insert('member_coupon', array_keys($arr))->values(array_values($arr))->execute();
                }
            }
            $record = [
                'member_id'    => $member['mid'],
                'equity_id'    => 5,
                'type'         => 3,
                'addtime'      => time(),
            ];
            DB::insert('member_grade_change_record', array_keys($record))->values(array_values($record))->execute();
        }
    }

    public static function get_equity($grade_id)
    {
        $equity = DB::select()->from('member_grade_equity')->where('grade_id', '=', $grade_id)->execute()->current();
        if(empty($equity['equity_id'])){
            return false;
        }
        $equity['equity_id'] = explode(',', $equity['equity_id']);
        //equity_id大于6的权益无用
        foreach ($equity['equity_id'] as $key => $value) {
            if ($value > 6) {
                unset($equity['equity_id'][$key]);
            }
        }
        if(count($equity['equity_id'])<1){
            return false;
        }

        return $equity;
    }
}